package genedit.view.graph;

import genedit.model.graph.GraphElement;
import genedit.model.graph.Link;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class Clipboard {
	private List<GraphElement> copiedElements;

	private static Clipboard instance = null;
	private XStream xstream;

	public XStream getXstream() {
		return xstream;
	}

	public void setXstream(XStream xstream) {
		this.xstream = xstream;
	}

	public static Clipboard getInstance() {
		if (instance == null)
			instance = new Clipboard();
		return instance;
	}

	public List<GraphElement> getCopiedElements() {
		if (copiedElements == null)
			copiedElements = new ArrayList<GraphElement>();
		return copiedElements;
	}

	public Iterator<GraphElement> getIteratorCopiedElements() {
		if (copiedElements == null)
			copiedElements = new ArrayList<GraphElement>();
		return copiedElements.iterator();
	}

	public void setCopiedElements(java.util.Collection<GraphElement> newCopiedElements) {
		removeAllCopiedElements();
		for (Iterator<GraphElement> iter = newCopiedElements.iterator(); iter.hasNext();) {
			GraphElement element = iter.next();
			addCopiedElements(element);
			if (element instanceof Link) {
				Link link = (Link) element;
				addCopiedElements(link.getStart().getParent());
				addCopiedElements(link.getEnd().getParent());
			}
		}
	}

	public void addCopiedElements(GraphElement newElementPainter) {
		if (newElementPainter == null)
			return;
		if (this.copiedElements == null)
			this.copiedElements = new ArrayList<GraphElement>();
		if (!this.copiedElements.contains(newElementPainter))
			this.copiedElements.add(newElementPainter);
	}

	public void removeCopiedElements(GraphElement oldElementPainter) {
		if (oldElementPainter == null)
			return;
		if (this.copiedElements != null)
			if (this.copiedElements.contains(oldElementPainter))
				this.copiedElements.remove(oldElementPainter);
	}

	public void removeAllCopiedElements() {
		if (copiedElements != null)
			copiedElements.clear();
	}

	private Clipboard() {
		xstream = new XStream(new DomDriver());
		xstream.omitField(GraphElement.class, "parent");
	}
}